import * as XLSX from 'xlsx'
import { TClass } from '../../../../../Types/education'
import { ElMessage, ElLoading } from 'element-plus'

// Excel表头映射
const headerMap = {
	学院: 'academy',
	专业: 'major',
	年级: 'grade',
	班级: 'classname',
	辅导员: 'counsellor',
	联系电话: 'phoneNumber'
}

/**
 * 导出Excel文件
 * @param data 要导出的数据
 * @param fileName 文件名
 */
export const exportToExcel = (data: TClass[], fileName: string = '班级信息表') => {
	console.log(data)

	try {
		// 转换数据格式
		const excelData = data.map((item) => ({
			学院: item.academy,
			专业: item.major,
			年级: `${item.grade}`,
			班级: item.classname,
			辅导员: item.counsellor,
			联系电话: item.phoneNumber
		}))

		// 创建工作簿
		const worksheet = XLSX.utils.json_to_sheet(excelData)
		const workbook = XLSX.utils.book_new()
		XLSX.utils.book_append_sheet(workbook, worksheet, '班级信息')

		// 导出文件
		XLSX.writeFile(workbook, `${fileName}.xlsx`)
		ElMessage.success('导出成功')
	} catch (error) {
		console.error('导出Excel失败:', error)
		ElMessage.error('导出失败，请重试')
	}
}

/**
 * 导入Excel文件
 * @param file 上传的文件
 * @returns Promise<{data: TClass[], preview: any[]}>
 */
export const importFromExcel = (file: File): Promise<{ data: TClass[]; preview: any[] }> => {
	return new Promise((resolve, reject) => {
		const reader = new FileReader()

		// 开始读取时显示全局loading
		const loadingInstance = ElLoading.service({
			lock: true,
			text: '正在读取文件...',
			background: 'rgba(0, 0, 0, 0.7)'
		})

		reader.onload = (e) => {
			try {
				const data = e.target?.result
				const workbook = XLSX.read(data, { type: 'binary' })
				const worksheet = workbook.Sheets[workbook.SheetNames[0]]
				const jsonData = XLSX.utils.sheet_to_json(worksheet)

				// 验证和转换数据
				const result: TClass[] = jsonData.map((row: any) => {
					// 验证必填字段
					for (const [zhKey, enKey] of Object.entries(headerMap)) {
						if (!row[zhKey]) {
							throw new Error(`${zhKey}不能为空`)
						}
					}

					// 转换数据格式
					return {
						academy: row['学院'],
						major: row['专业'],
						grade: parseInt(row['年级']),
						classname: row['班级'],
						counsellor: row['辅导员'],
						phoneNumber: row['联系电话'].toString()
					}
				})

				// 生成预览数据
				const preview = jsonData.map((row: any, index: number) => ({
					index: index + 1,
					...row
				}))

				loadingInstance.close()
				resolve({
					data: result,
					preview: preview
				})
			} catch (error) {
				loadingInstance.close()
				console.error('导入Excel失败:', error)
				reject(error)
				ElMessage.error(`导入失败：${error instanceof Error ? error.message : '未知错误'}`)
			}
		}

		reader.onerror = (error) => {
			loadingInstance.close()
			reject(error)
			ElMessage.error('文件读取失败')
		}

		reader.readAsArrayBuffer(file)
	})
}
